package cn.le.helper;

import cn.le.beans.dto.JobInfoDTO;
import cn.le.beans.vo.JobInfoVO;
import cn.le.exception.BizException;
import cn.le.quartz.QuartzExectueJob;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Component
public class QuartzManager {

    @Autowired
    private Scheduler scheduler;

    /**
     * 添加任务
     * @param jobInfoVOList
     */
    public void addJobs(List<JobInfoVO> jobInfoVOList) throws BizException {
        int size = jobInfoVOList.size();
        List<JobKey> doneJobs = new ArrayList<>(size);
        for (int i = 0; i < size; i++ ){
            JobInfoVO jobInfoVO = jobInfoVOList.get(i);

            JobDataMap dataMap = new JobDataMap();
            dataMap.put("data",jobInfoVO.getJobInfo());

            JobKey jobKey = jobInfoVO.getJobKey();
            JobDetail jobDetail = JobBuilder.newJob(QuartzExectueJob.class).withIdentity(jobKey).build();

            List<TriggerKey> triggerKeyList = jobInfoVO.getTriggerKeys();
            for (int j = 0,triSize = triggerKeyList.size(); i < triSize; i++ ) {
                CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(jobInfoVO.getJobInfo().getStrategys().get(j));
                Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKeyList.get(j)).usingJobData(dataMap)
                        .withSchedule(cronScheduleBuilder).build();
                try {
                    scheduler.scheduleJob(jobDetail,trigger);
                } catch (SchedulerException e) {
                    //删除已经添加成功的了的
                    if (!CollectionUtils.isEmpty(doneJobs)) {
                        deleteJobs(doneJobs);
                    }
                    throw  new BizException("创建任务失败");
                }
            }
            doneJobs.add(jobKey);
        }
    }


    public JobKey getJobKey(String jobName,String appName){
        return new JobKey(jobName+"_"+appName);
    }

    public TriggerKey getTriggerKey(String jobName,String appName,int index){
        return new TriggerKey(jobName+"_"+appName+"_"+index);
    }

    /**
     * 删除任务
     * @param jobKeyList
     */
    public void deleteJobs(List<JobKey> jobKeyList)throws BizException {
        try {
            for (JobKey jobKey:jobKeyList) {
                List<? extends Trigger> triggersOfJob = scheduler.getTriggersOfJob(jobKey);
                for (Trigger trigger : triggersOfJob) {
                    //暂停触发器
                    scheduler.pauseTrigger(trigger.getKey());
                    //删除触发器
                    scheduler.unscheduleJob(trigger.getKey());
                }
                scheduler.deleteJob(jobKey);
            }
        } catch (SchedulerException e) {
            throw new BizException("删除失败!");
        }
    }

    /**
     * 暂停任务
     * @param jobKeyList
     */
    public void suspendJobs(List<JobKey> jobKeyList) throws BizException {
        try {
            for (JobKey jobKey : jobKeyList){
                scheduler.pauseJob(jobKey);
            }
        } catch (SchedulerException e) {
            throw new BizException("暂停失败!");
        }
    }

    /**
     *恢复任务
     * @param jobKeyList
     * @throws BizException
     */
    public void resumeJobs(List<JobKey> jobKeyList) throws BizException {
        try {
            for (JobKey jobKey : jobKeyList){
                scheduler.resumeJob(jobKey);
            }
        } catch (SchedulerException e) {
            throw new BizException("回复失败!");
        }
    }

    /**
     * 更新任务
     * @param jobInfoVOList
     */
    public void rescheduleJobs(List<JobInfoVO> jobInfoVOList) throws BizException {
        for (int i = 0,size = jobInfoVOList.size(); i < size; i++) {
            JobInfoVO jobInfoVO = jobInfoVOList.get(i);
            JobInfoDTO jobInfo = jobInfoVO.getJobInfo();
            List<TriggerKey> triggerKeys = jobInfoVO.getTriggerKeys();
            try {
                for (int j = 0,triSize = triggerKeys.size(); j < triSize; j++) {
                    CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(jobInfo.getStrategys().get(i));
                    Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKeys.get(i))
                            .withSchedule(cronScheduleBuilder).build();
                    scheduler.rescheduleJob(triggerKeys.get(i),trigger);
                }
            } catch (SchedulerException e) {
                throw new BizException("更新任务失败");
            }
        }
    }


}
